﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WMM.Tapioca.Linkbase;
using System.Xml.Linq;
using Saxon.Api;

namespace WMM.Tapioca.Formula
{
    /// <summary>
    /// The base class of  FactVariable and GeneralVariable.
    /// </summary>
    public class Variable : FormulaResource
    {
        private bool bindAsSequence;

        /// <returns> A variable binds as a sequence if it has a @bindAsSequence attribute
        /// equal to true.  Otherwise, it does not bind as a sequence. </returns>
        public bool BindAsSequence
        {
            get { return bindAsSequence; }
            set { bindAsSequence = value; }
        }

        private int fallbackValue;

        /// <returns>A fallback value is the value of a fact variable that has been determined on the 
        /// basis of the content of the @fallbackValue attribute.</returns>
        public int FallbackValue
        {
            get { return fallbackValue; }
            set { fallbackValue = value; }
        }

        private string fallbackString;

        public string FallbackString
        {
            get { return fallbackString; }
            set { fallbackString = value; }
        }

        public Variable() { }

        /// <summary>
        /// Constructor.
        /// </summary>
        public Variable(Resource resource)
            : base(resource)
        {
            foreach (XAttribute attr in resource.ResourceXElement.Attributes())
            {
                if (attr.Name.LocalName.Equals("bindAsSequence"))
                {
                    BindAsSequence = Boolean.Parse(attr.Value);
                }
            }
        }

        protected string EvaluateExpression(string expression)
        {
            // Create a Processor instance.
            Processor processor = new Processor();

            //RegisterExtensionFunctions(processor);

            // Create the XPath expression.
            XPathCompiler compiler = processor.NewXPathCompiler();
            //compiler.DeclareNamespace("xfi", "http://www.xbrl.org/2008/function/instance");

            if (expression == "()")
            {
                return string.Empty;
            }
            XPathSelector selector = compiler.Compile(expression).Load();

            //SetContextItem(processor, selector);

            string result = selector.EvaluateSingle().ToString();

            return result;
        }
    }
}
